package quercus;

import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.caucho.quercus.QuercusContext;
import com.caucho.quercus.env.Env;
import com.caucho.quercus.env.GoogleEnv;
import com.caucho.quercus.lib.db.JdbcDriverContext;
import com.caucho.quercus.page.QuercusPage;
import com.caucho.vfs.GoogleMergePath;
import com.caucho.vfs.MergePath;
import com.caucho.vfs.Path;
import com.caucho.vfs.WriteStream;

/**
 * Facade for the PHP language.
 */
@SuppressWarnings("serial")
public class MondayScriptingContext extends QuercusContext implements
		Serializable {
	/**
	 * Constructor.
	 */
	public MondayScriptingContext() {
	}

	@Override
	public void init() {
		String mode = System
				.getProperty("com.google.appengine.tools.development.ApplicationPreparationMode");

		boolean isGsDisabled = "true".equals(mode);

		if (!isGsDisabled) {
			String gsBucket = getIniString("google.cloud_storage_bucket");

			if (gsBucket != null) {
				Path stdPwd = getPwd();

				GoogleMergePath mergePwd = new GoogleMergePath(stdPwd,
						gsBucket, true);
				setPwd(mergePwd);

				Path webInfDir = getWebInfDir();
				Path gsWebInfDir = mergePwd.getGooglePath().lookup("WEB-INF");
				MergePath mergeWebInf = new MergePath(gsWebInfDir, webInfDir);

				setWebInfDir(mergeWebInf);
			}
		}

		super.init();

		JdbcDriverContext jdbcDriverContext = getJdbcDriverContext();

		String driver = getIniString("google.jdbc_driver");

		if (driver == null) {
			driver = "com.google.appengine.api.rdbms.AppEngineDriver";
		}

		jdbcDriverContext.setDefaultDriver(driver);
		jdbcDriverContext.setDefaultUrlPrefix("jdbc:google:rdbms://");
		jdbcDriverContext.setDefaultEncoding(null);
		jdbcDriverContext.setProtocol("mysql", driver);
		jdbcDriverContext.setProtocol("google:rdbms", driver);
	}

	@Override
	public Env createEnv(QuercusPage page, WriteStream out,
			HttpServletRequest request, HttpServletResponse response) {
		return new GoogleEnv(this, page, out, request, response);
	}
}
